<?php

namespace app\admin\controller;

use think\Request;
use think\Db;
use think\Cache;

class Goods extends Common 
{
	/**
	 * 商品管理主页
	 */
	public function index()
	{	
		$page      = input('?get.page') ? input('get.page') : 1;
		$order     = input('?get.order') ? input('get.order') : Null;
		$keywords  = input('?get.keywords') ? trim(input('get.keywords')) : Null;
		$pageSize  = 2;
		$totalRows = $this->_getGoodsCount($keywords);
		$totalPage = ceil($totalRows/$pageSize);
		$list      = DB::name('goods')
			->field('g.id, gName, gSN, gNum, mPrice, iPrice, gDesc, pubTime, isShow, isHot, cName')
			->alias('g')
			->join('__CATE__ c','g.cId = c.id', 'LEFT')
			->where('gName', 'like', "%$keywords%")
			->order($order)
			->page($page, $pageSize)
			->select();
		$count = count($list);
		for ($i=0; $i < $count; $i++) { 
			$list[$i]['imgPath'] = $this->_getAllImgPath($list[$i]['id']);
		}
		dump($totalRows);
		$this->assign('list', $list);
		$this->assign('page', $page);
		$this->assign('pageSize', $pageSize);
		$this->assign('totalPage', $totalPage);
		return $this->fetch();
	}

	/**
	 * 添加商品
	 */
	public function add()
	{	
		if (Request::instance()->isPost()) {
			$gName   = input('post.gName');
			$cId     = input('post.cId');
			$gSn     = input('post.gSn');
			$gNum    = input('post.gNum');
			$mPrice  = input('post.mPrice');
			$iPrice  = input('post.iPrice');
			$gDesc   = input('post.gDesc');
			$pubTime = time();

			$data['gName']   = $gName;
			$data['cId']     = $cId;
			$data['gSn']     = $gSn;
			$data['mPrice']  = $mPrice;
			$data['iPrice']  = $iPrice;
			$data['gDesc']   = $gDesc;
			$data['pubTime'] = $pubTime;

			$files = request()->file('image'); 
			$imgPath = array();
			$picPath = ROOT_PATH . 'public' . DS . 'uploads' . DS . 'picture' . DS;

			if (!is_dir($picPath . 'goods_50' . DS . date("Ymd"))) {
				mkdir($picPath . 'goods_50' . DS . date("Ymd"));
				mkdir($picPath . 'goods_150' . DS . date("Ymd"));
				mkdir($picPath . 'goods_800' . DS . date("Ymd"));
			}
			foreach ($files as $img) {
				$info = $img->move(ROOT_PATH . 'public' . DS . 'uploads' . DS . 'picture' . DS . 'goods');
				if ($info) {
					$path = $info->getSavename();
					$imgPath[] = $path;
				} else {
					return $this->error('图片上传失败');
				}
				$image = \think\Image::open($picPath . 'goods' .DS . $path);	
				$image->thumb(800,800,\think\Image::THUMB_FILLED)->save($picPath . 'goods_800' . DS . $path);
				$image->thumb(150,150,\think\Image::THUMB_FILLED)->save($picPath . 'goods_150' . DS . $path);
				$image->thumb(50 ,50 ,\think\Image::THUMB_FILLED)->save($picPath . 'goods_50' . DS . $path);
			}

			$id = Db::name('goods')->insertGetId($data);
			foreach ($imgPath as $path) {
				$albumData[] = array(
							'gid' => $id,
							'albumPath' => $path
					);
			}
			$id2 = DB::name('album')->insertAll($albumData);

	  		if($id && $id2) {
	  			return $this->success('操作成功','/admin/goods/index');
	  		} else {
	  			return $this->error('添加失败');
	  		}	
 		} else {
			$cateList = DB::name('cate')->select();
			$this->assign('cateList', $cateList);
			return $this->fetch();
		}
		
	}

	/**
	 * 删除商品
	 */
	public function delete()
	{
		$id = input('get.id');
		$num1 = $this->_deleteImgByGoodsId($id);
		$num2 = DB::name('goods')->where('id', $id)->delete();
		if ($num2) {
			return $this->success('删除成功', '/admin/goods/index');
		}else{
			return $this->error('删除失败');
		}
	}

	/**
	 * 编辑商品信息
	 */
	public function edit()
	{
		if (Request::instance()->isPost()) {
			$id      = input('get.id');
			$gName   = input('post.gName');
			$cId     = input('post.cId');
			$gSn     = input('post.gSn');
			$gNum    = input('post.gNum');
			$mPrice  = input('post.mPrice');
			$iPrice  = input('post.iPrice');
			$gDesc   = input('post.gDesc');

			$data = array();
			$data['gName']   = $gName;
			$data['cId']     = $cId;
			$data['gSn']     = $gSn;
			$data['mPrice']  = $mPrice;
			$data['iPrice']  = $iPrice;
			$data['gDesc']   = $gDesc;
			$data['gNum']    = $gNum;

			$num = DB::name('goods')->where('id', $id)->update($data);
			if ($num) {
				return $this->success('更新成功', '/admin/goods/index');
			}else{
				return $this->error('更新失败');
			}
		}else{
			$id = input('get.id');
			$info = DB::name('goods')->field('gName, gSn, gNum, mPrice, iPrice, gDesc')->where('id', $id)->find();
			$cateList = DB::name('cate')->select();

			$this->assign('id', $id);
			$this->assign('info',$info);
			$this->assign('cateList', $cateList);
			return $this->fetch();
		}
	}	

	/**
	 * 获取商品的所有图片路径信息
	 * @param  int   $id 商品id
	 * @return array     图片路径数组
	 */
	private function _getAllImgPath($id)
	{	
		$name    = 'goods_imgPath_'.$id;
		$imgPath = Cache::get($name);
		if ($imgPath == 0) {
			$imgPath = DB::name('album')->field('albumPath')->where('gid',$id)->select();
			Cache::set($name, $imgPath, 3600);
		}
		return $imgPath;
	}

	/**
	 * 根据商品id删除图片
	 * 可以根据情况管理远程图片站
	 * @param  int $id 商品id
	 * @return int     数据库商品表中影响的数据条数
	 */
	private function _deleteImgByGoodsId($id)
	{
		$info = DB::name('album')->field('albumPath')->where('gid', $id)->select();
		$imgRootPath = ROOT_PATH . 'public' . DS . 'uploads' . DS . 'picture' . DS . 'goods';
		foreach ($info as $path) {
			$truePath = $imgRootPath . DS . $path['albumPath'];
			unlink($truePath);
		}
		$nums = DB::name('album')->where('gid', $id)->delete();
		return $nums;
	}

	/**
	 * 获取商品总数量
	 * @return integer
	 */
	private function _getGoodsCount($keywords)
	{	
		$name = 'goods_count_' . $keywords;
		$res  = Cache::get($name);
		if ($res == false) {
			$res = DB::name('goods')->where('gName', 'like', "%$keywords%")->count();
			Cache::set($name, $res, 60);
		}
		return $res;
	}
}





